import { defineStore } from 'pinia';
import { computed, ref, unref } from 'vue';

import { useI18n } from '@/locale/index';
import themeJson from '@/theme.json';
import { getIsTabbar } from '@/utils';
import { ThemeInfo, ThemeStyle } from '#/store';

/** 主题信息 Theme information */
export const themeInfo: ThemeInfo = themeJson as ThemeInfo;

/** 主题状态 */
interface ThemeState {
  /** 主题 */
  theme: 'light' | 'dark' | 'auto';
}

/** 初始状态 */
const initState: ThemeState = {
  /** 主题 */
  theme: 'auto',
};

/** 当前主题存储 */
const useCurrThemeStore = defineStore(
  'app-theme-current',
  () => {
    /** 当前主题信息 */
    const currTheme = ref<'light' | 'dark'>('light');

    /** 获取当前主题 */
    const getCurrentTheme = computed<'light' | 'dark'>(() => unref(currTheme));
    /** 获取主题样式 */
    const getThemeStyle = computed<ThemeStyle>(() => {
      if (getCurrentTheme.value === 'dark') {
        return themeInfo.dark;
      } else {
        return themeInfo.light;
      }
    });

    /** 设置当前主题 */
    const setCurrentTheme = (theme: 'light' | 'dark') => {
      currTheme.value = theme;
      // NavigationBar
      uni.setNavigationBarColor({
        backgroundColor: getThemeStyle.value.navigationBarBackgroundColor,
        frontColor: getThemeStyle.value.navigationBarTextStyle,
      });
      // TabBar
      if (getIsTabbar()) {
        uni.setTabBarStyle({
          backgroundColor: getThemeStyle.value.tabBarBackgroundColor,
          borderStyle: getThemeStyle.value.tabBarBorderStyle,
        });
      }
    };

    return {
      /** 当前主题信息 */
      state: currTheme,
      /** 获取当前主题 */
      getCurrentTheme,
      /** 获取主题样式 */
      getThemeStyle,
      /** 设置当前主题 */
      setCurrentTheme,
    };
  },
  {
    persist: false, // 如果需要持久化就写 true, 不需要持久化就写 false（或者去掉这个配置项）。
  },
);

/** 主题存储 */
export const useThemeStore = defineStore(
  'app-theme',
  () => {
    /** 主题信息 */
    const state = ref<ThemeState>({ ...initState });

    const { t } = useI18n();
    const currThemeStore = useCurrThemeStore();

    /** 获取主题 */
    const getTheme = computed(() => unref(state).theme);
    /** 获取当前主题 */
    const getCurrentTheme = computed<'light' | 'dark'>(() => currThemeStore.getCurrentTheme);
    /** 获取主题样式 */
    const getThemeStyle = computed<ThemeStyle>(() => currThemeStore.getThemeStyle);

    /** 获取主题列表 */
    const getThemeList = computed(() => {
      return [
        {
          value: 'light',
          label: t('layout.theme.light'),
          disabled: false,
          icon: 'i-tdesign:mode-light',
        },
        {
          value: 'dark',
          label: t('layout.theme.dark'),
          disabled: false,
          icon: 'i-tdesign:mode-dark',
        },
        {
          value: 'auto',
          label: t('layout.theme.auto'),
          disabled: false,
          icon: 'i-mdi:theme-light-dark',
        },
      ];
    });

    /** 当前主题 */
    const currentTheme = () => {
      const currTheme = unref(state).theme;
      if (currTheme === 'auto') {
        const systemInfo = uni.getSystemInfoSync();
        // const theme1 = systemInfo.theme;
        // const osTheme = systemInfo.osTheme;
        // const hostTheme = systemInfo.hostTheme;
        // console.log('theme', { theme1, osTheme, hostTheme });
        let theme = systemInfo.theme;
        if (theme === 'light' || theme === 'dark') {
          return theme;
        } else {
          theme = systemInfo.hostTheme;
          if (theme === 'light' || theme === 'dark') {
            return theme;
          } else {
            theme = systemInfo.osTheme;
            if (theme === 'light' || theme === 'dark') {
              return theme;
            } else {
              return 'light';
            }
          }
        }
      } else {
        return currTheme;
      }
    };

    /** 设置主题 */
    const setTheme = (theme: 'light' | 'dark' | 'auto') => {
      state.value = { ...state.value, theme };

      currThemeStore.setCurrentTheme(currentTheme());
      // #ifdef APP
      try {
        plus.nativeUI.setUIStyle(theme); // 'light'表示浅色外观样式 只在APP有效
      } catch (err) {
        console.error('setUIStyle', err);
      }
      // #endif
    };

    onMounted(() => {
      // 主题设置
      // console.log('主题设置');
      currThemeStore.setCurrentTheme(currentTheme());
      // 监听系统主题状态变化
      uni.onThemeChange(({ theme }) => {
        // console.log('系统主题状态变化', theme);
        if (theme && getTheme.value === 'auto') {
          currThemeStore.setCurrentTheme(theme);
        }
      });
    });

    return {
      /** 主题信息 */
      state,
      /** 获取主题 */
      getTheme,
      /** 获取当前主题 */
      getCurrentTheme,
      /** 获取主题样式 */
      getThemeStyle,
      /** 获取主题列表 */
      getThemeList,
      /** 当前主题 */
      currentTheme,
      /** 设置主题 */
      setTheme,
      /** 设置当前主题 */
      setCurrentTheme: currThemeStore.setCurrentTheme,
    };
  },
  {
    persist: true, // 如果需要持久化就写 true, 不需要持久化就写 false（或者去掉这个配置项）。
  },
);
